import { createStore } from 'vuex'
import { login, getUserProfile } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    user: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_USER: (state, user) => {
    state.user = Object.assign(state.user, user)
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}
const actions = {
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      login(data)
        .then(
          res => {
            const { token } = res.data
            commit('SET_TOKEN', token)
            setToken(token)
            resolve()
          },
          err => {
            reject(new Error(err))
          }
        )
        .catch(error => {
          reject(new Error(error))
        })
    })
  },
  // 获取用户信息
  getUserProfile({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserProfile()
        .then(res => {
          if (!res) {
            return reject(new Error('Verification failed, please Login again.'))
          }
          commit('SET_USER', res.data)
          resolve(res)
        })
        .catch(error => {
          reject(new Error(error))
        })
    })
  },

  logout({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

const getters = {
  token: state => state.token,
  avatar: state => state.user.photo || '',
  name: state => state.user.name || ''
}
export default createStore({
  state,
  mutations,
  actions,
  getters,
  modules: {}
})
